package services

import (
	"fmt"
	"peilian-api/app/global/databases/tables"
	"peilian-api/app/global/variable"
	"strconv"
)

func FindQuestionsBySessionId(sessionId int) ([]tables.RealQues, error) {
	var questions []tables.RealQues
	err := variable.DB.MySQL.Preload("Question").Order("id").Find(&questions, "session_id = ?", sessionId).Error
	if err != nil {
		return nil, err
	}
	var session tables.Session
	if err := variable.DB.MySQL.First(&session, sessionId).Error; err == nil {
		if session.CareerID != tables.QCivilServant {
			return questions[1:], nil
		}
	}
	return questions, nil // 第一道为自我介绍题目，不参与评分
}

func FetchTotalScoreBySessionId(sessionId int) float64 {
	var result []float64
	var sum float64
	err := variable.DB.MySQL.Table("real_question").Where("session_id = ?", sessionId).Pluck("language_score", &result).Error
	if err != nil {
		return 0.00
	}
	length := len(result)
	if length == 0 {
		return 0.00
	}
	for _, v := range result {
		sum += v
	}

	score, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", sum/float64(length)), 64)
	return score
}
